/**
 * @description 所有人可使用的参数配置列表
 * @params hideMenu: 是否隐藏当前路由结点不在导航中展示
 * @params alwayShow: 只有一个子路由时是否总是展示菜单，默认false
 */
import { reactive }                           from "vue"
import { createRouter, createWebHashHistory } from "vue-router"
import NProgress                              from "@/utils/system/nprogress"
import { changeTitle }                        from "@/utils/system/title"
import { useKeepAliveStore }                  from "@/store/keepAlive.js"
import { useUserStore }                       from "@/store/user.js"

import Dashboard   from "@/router/modules/dashboard.js"
import System      from "./modules/system"
import Descriptive from "@/router/modules/descriptive.js"
import Grouping    from "@/router/modules/grouping.js"
import Exploratory from "@/router/modules/exploratory.js"
import TimeSeries  from "@/router/modules/timeseries.js"
import Spatial     from "@/router/modules/spatial.js"
import Group       from "@/router/modules/group.js"
import Structure   from "@/router/modules/structure.js"

NProgress.configure({ showSpinner: false })

/**
 * 路由配置
 */
let modules = reactive([
    ...Dashboard,
    ...System,
    ...Descriptive,
    ...Grouping,
    ...Exploratory,
    ...TimeSeries,
    ...Spatial,
    ...Group,
    ...Structure,
])

const router = createRouter({
    history: createWebHashHistory(),
    routes : modules,
})

// 无需登录也能访问的白名单
const whiteList = [ "/login" ]

let userStore
// 路由跳转前的监听操作
router.beforeEach((to, _from, next) => {
    NProgress.start()
    if(!userStore){
        userStore = useUserStore()
    }
    
    // 已登录,放行
    if(userStore.token){
        to.meta.title ? (changeTitle(to.meta.title)) : "" // 动态title
        if(to.path === "/login"){
            next("/")
            return
        }
        next()
    }
    // 未登录,只允许访问白名单
    else if(whiteList.includes(to.path)){
        to.meta.title ? (changeTitle(to.meta.title)) : "" // 动态title
        next()
    }
    // 其他必须登录
    else{
        next("/login") // 全部重定向到登录页
        to.meta.title ? (changeTitle(to.meta.title)) : "" // 动态title
    }
})

let keepAliveStore
// 路由跳转后的监听操作
router.afterEach((to, _from) => {
    // 如果需要缓存,则缓存目录
    if(!keepAliveStore){
        keepAliveStore = useKeepAliveStore()
    }
    const keepAliveComponentsName = keepAliveStore.keepAliveComponentsName || []
    const name                    = to.matched[to.matched.length - 1].components.default.name
    if(to.meta && to.meta.cache && name && !keepAliveComponentsName.includes(name)){
        keepAliveStore.add(name)
    }
    NProgress.done()
})

export {
    modules,
}

export default router
